# -*- coding: utf-8 -*-
"""
@ Created on 2024-06-14 12:23
---------
@summary: 字典类型CRUD操作
---------
@author: Lsaiah
"""

from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator
from datetime import datetime
from typing import Optional, List, Dict, Any


class DictType(Model):
    """字典类型模型"""
    id = fields.IntField(pk=True, description="字典类型ID")
    name = fields.CharField(max_length=100, description="字典类型名称")
    code = fields.CharField(max_length=50, unique=True, description="字典类型编码")
    description = fields.CharField(max_length=200, null=True, description="字典类型描述")
    is_system = fields.BooleanField(default=False, description="是否系统字典类型")
    is_deleted = fields.BooleanField(default=False, description="是否删除") 
    is_active = fields.BooleanField(default=True, description="是否激活")
    sort_order = fields.IntField(default=0, description="排序")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        table = "system_dict_type"
        table_description = "系统字典类型表"

    def __str__(self):
        return f"DictType(id={self.id}, name={self.name}, is_system={self.is_system}, is_active={self.is_active})"


# Pydantic 模型
DictType_Pydantic = pydantic_model_creator(DictType, name="DictType")
DictTypeIn_Pydantic = pydantic_model_creator(
    DictType, 
    name="DictTypeIn", 
    exclude_readonly=True,
    exclude=("id", "created_at", "updated_at")
)
DictTypeUpdate_Pydantic = pydantic_model_creator(
    DictType, 
    name="DictTypeUpdate", 
    exclude_readonly=True,
    exclude=("id", "created_at", "updated_at")
)


class DictTypeCRUD:
    """字典类型CRUD操作类"""
    
    @staticmethod
    async def create(data: Dict[str, Any]) -> DictType:
        """创建字典类型"""
        return await DictType.create(**data)
    
    @staticmethod
    async def get_by_id(id: int) -> Optional[DictType]:
        """根据ID获取字典类型"""
        return await DictType.get_or_none(id=id)
    
    @staticmethod
    async def get_by_code(code: str) -> Optional[DictType]:
        """根据编码获取字典类型"""
        return await DictType.get_or_none(code=code)
    
    @staticmethod
    async def get_list(
        skip: int = 0, 
        limit: int = 10, 
        search: Optional[str] = None,
        **filters
    ) -> List[DictType]:
        """获取字典类型列表"""
        query = DictType.all()
        
        if search:
            query = query.filter(
                name__icontains=search
            ) | query.filter(
                code__icontains=search
            ) | query.filter(
                description__icontains=search
            )
        
        # 处理其他过滤条件
        for key, value in filters.items():
            if value is not None:
                query = query.filter(**{key: value})
        
        return await query.offset(skip).limit(limit).order_by("sort_order", "-created_at")
    
    @staticmethod
    async def count_list(
        search: Optional[str] = None,
        **filters
    ) -> int:
        """统计字典类型数量"""
        query = DictType.all()
        
        if search:
            query = query.filter(
                name__icontains=search
            ) | query.filter(
                code__icontains=search
            ) | query.filter(
                description__icontains=search
            )
        
        # 处理其他过滤条件
        for key, value in filters.items():
            if value is not None:
                query = query.filter(**{key: value})
        
        return await query.count()
    
    @staticmethod
    async def update(id: int, update_data: Dict[str, Any]) -> Optional[DictType]:
        """更新字典类型"""
        dict_type = await DictType.get_or_none(id=id)
        if dict_type:
            await dict_type.update_from_dict(update_data)
            await dict_type.save()
        return dict_type
    
    @staticmethod
    async def delete(id: int) -> bool:
        """删除字典类型"""
        dict_type = await DictType.get_or_none(id=id)
        if dict_type:
            await dict_type.update_from_dict({"is_deleted": True})
            await dict_type.save()
            return True
        return False
